<template @wheel="handlePageChange">
  <tiny-row class="header row-item" :flex="true">
    <tiny-col :span="9">
      <div class="search-header">
        <tiny-search
            mini
            clearable
            transparent
            v-model="searchPost"
            @search="handleSearchPostList"
            placeholder="请输入话题"
        >
        </tiny-search>
      </div>
    </tiny-col>
  </tiny-row>
  <tiny-row class="main row-item" :flex="true" style="margin-left:1%">
    <tiny-col :span="2" class="userCol">
      <div class="user-info">
        <span style="font-size:15px;font-weight:bold;">我在贴吧</span>
        <div v-if="currentUser" class="base">
          <img :src="currentUser.avatar" alt="头像" width="70" height="70"/>
          <div style="display:flex;flex-direction: column;margin-left: 15px;">
            <span class="nickname">
              <tiny-tag>{{ currentUser.nickname }}</tiny-tag>
            </span>
          </div>
        </div>
        <div v-else><span style="color:#949494">需要登陆才可查看</span></div>
        <span v-if="currentUser" style="font-size:15px;font-weight:bold;">兴趣专栏</span>
        <div v-if="currentUser" class="interesting-column">
          <tiny-tag
              v-for="column in interestingColumn"
              :key="column.id"
              style="margin-right:8px;margin-bottom:8px"
              :type="column.type"
          >
            <tag-one theme="outline" size="17" fill="#333" :strokeWidth="2"/>
            <span style="margin-left:5px">{{ column.name }}</span>
          </tiny-tag>
        </div>
      </div>
    </tiny-col>
    <tiny-col :span="10">
      <div class="column-page">
        <div class="page-header">
          <div class="title">
            <planet theme="two-tone" size="24" :fill="['#333' ,'#2F88FF']" :strokeWidth="2"/>
            <span style="margin-left:3px;font-size:17px;font-weight:bold;">专栏分类</span>
          </div>
          <div class="page-arrow">
            <left-c @click="prePage" theme="multi-color" size="20" :fill="['#e9e8eb' ,'#e9e8eb' ,'#333' ,'#43CCF8']"
                    :strokeWidth="2"/>
            <span
                style="margin-left:5px;margin-right: 5px;color:#949494;">{{ columnPageNum }}/{{
                columnPageTotal
              }}</span>
            <right-c @click="nextPage" theme="multi-color" size="20" :fill="['#e9e8eb' ,'#e9e8eb' ,'#333' ,'#43CCF8']"
                     :strokeWidth="2"/>
          </div>
        </div>
        <div class="page-main">
          <div class="column" v-for="column in columnList" :key="column.id" @click="toPostList(column.id)">
            <img :src="column.coverImage" alt="封面" width="60" height="60"/>
            <div class="base">
              <span class="name">{{ column.name }}</span>
              <span class="access-number">
                <me theme="outline" size="13" fill="#949494" :strokeWidth="2"/>
                <span v-if="column.accessNumber">
                  {{ column.accessNumber }}
                </span>
                <span v-else>0</span>
              </span>
              <span class="comment-number">
                <comment theme="outline" size="13" fill="#949494" :strokeWidth="2"/>
                {{ column.commentNumber }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="post-list">
          <div class="nav">
            <div>最新发帖</div>
          </div>
          <div class="post-info" v-for="post in postList" :key="post.id">
            <router-link :to="{name:'PostDetail',params:{postId:post.id}}">{{ post.title }}</router-link>
            <img :src="post.coverImage" alt="封面" width="150"/>
            <div style="display:flex;font-size:13px;margin-top:10px">
              <img src="../../public/time.png" alt="封面" width="16" height="16" style="margin-right:5px"/>
              <span style="color:#949494">{{ post.createTime }}</span>
            </div>
            <hr style="color:red"/>
          </div>
        </div>
        <div class="post-rank">
          <div class="nav">
            <div>贴吧热议榜</div>
          </div>
          <div
              class="rank"
              v-for="(rank,index) in rankPostList"
              :key="rank.id"
              @click="toPostDetail(rank.id)"
          >
            <span>
              <span
                  v-if="index < 3"
                  style="background-color:#ff7f42;color:white;display: inline-block;width:20px;height:20px;text-align: center;margin-right:5px;"
              >
                {{ index + 1 }}
              </span>
              <span
                  v-else
                  style="display: inline-block;width:20px;height:20px;text-align: center;margin-right:5px;">{{ index + 1 }}</span>
              <span v-if="rank.title.length > 12" class="rank-title">
              {{ rank.title.substring(0, 13) }}...
              </span>
              <span v-else class="rank-title">
                {{ rank.title }}
              </span>
            </span>
            <div style="display: flex;align-items: center">
              <preview-open theme="outline" size="20" fill="#333" :strokeWidth="2"/>
              <span style="color:#949494">{{ rank.accessNumber }}</span>
            </div>
          </div>
        </div>
      </div>
    </tiny-col>
  </tiny-row>
</template>

<script setup>
import {Row as TinyRow, Col as TinyCol, Search as TinySearch, Tag as TinyTag, Modal} from '@opentiny/vue'
import {TagOne, Planet, LeftC, RightC, Me, Comment, PreviewOpen} from '@icon-park/vue-next'
import {onMounted, onUnmounted, ref} from 'vue'
import {useHeaderSearchStore} from "../store/useHeaderSearchStore.js";
import {useRouter} from "vue-router";
import request from "../utils/request.js";
import {userName} from "../config/index.js";
import {debounce} from "lodash";


document.title = '唯忆社区-贴吧'
const router = useRouter()
const store = useHeaderSearchStore()
const {updateExistFlag} = {...store}
updateExistFlag() // 隐藏搜索框
const searchPost = ref('')
const interestingColumn = ref([])
const tagType = ['success', 'info', 'warning', 'danger']
const columnPageNum = ref(1)
const columnPageSize = ref(12)
const columnPageTotal = ref(0)
const pageNum = ref(1)
const pageSize = ref(150000) // 暂不处理分页
const pageTotal = ref(0)
const columnList = ref([])
const postList = ref([])
const rankPostList = ref([])
const currentUser = localStorage.getItem(userName) ? JSON.parse(localStorage.getItem(userName)) : null


// todo 处理分页
// const handlePageChange = debounce((event) => {
//   if (event.deltaY > 0) {
//     // 判断是否还继续分页
//     if (postList.value.length !== pageTotal.value) {
//       pageNum.value++
//       request.get('/api/contents/posts/pageByTitle', {
//         params: {
//           title: searchPost.value,
//           pageNum: pageNum.value,
//           pageSize: pageSize.value
//         }
//       }).then(res => {
//         if (res.code === 1) {
//           postList.value = [...postList.value, ...res.data.records]
//         } else {
//           Modal.message({message: res.message, status: 'error'})
//         }
//       })
//     } else {
//       Modal.message({message: '已经到底了', status: 'warning', duration: 1500})
//       return
//     }
//   }
// }, 100)
//
// onMounted(() => {
//   window.addEventListener('wheel', handlePageChange);
// });
//
// onUnmounted(() => {
//   window.removeEventListener('wheel', handlePageChange);
// });

// 跳转帖子详情
const toPostDetail = (postId) => {
  const {href} = router.resolve({name: 'PostDetail', params: {postId}})
  window.open(href, '_blank')
}

// 搜索帖子
const handleSearchPostList = () => {
  request.get('/api/contents/posts/pageByTitle', {
    params: {
      title: searchPost.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
  }).then(res => {
    if (res.code === 1) {
      postList.value = res.data.records
      pageTotal.value = res.data.total
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
handleSearchPostList()

// 查询贴吧热议榜
const queryHotPostList = () => {
  request.get('/api/contents/posts/hotPost').then(res => {
    if (res.code === 1) {
      rankPostList.value = res.data
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryHotPostList()

// 向后翻页专栏
const nextPage = () => {
  if (columnPageNum.value === columnPageTotal.value) {
    return
  } else {
    columnPageNum.value++
    queryColumn()
  }
}

// 向前翻页专栏
const prePage = () => {
  if (columnPageNum.value === 1) {
    return
  } else {
    columnPageNum.value--
    queryColumn()
  }
}

// 查询专栏
const queryColumn = () => {
  request.get('/api/contents/posts/special-column/page', {
    params: {
      pageNum: columnPageNum.value,
      pageSize: columnPageSize.value,
    }
  }).then(res => {
    if (res.code === 1) {
      columnList.value = res.data.records
      columnPageTotal.value = res.data.total / columnPageSize.value < 1 ? 1 : Math.ceil(res.data.total / columnPageSize.value)
    } else {
      Modal.message({message: res.message, status: 'error'})
    }
  })
}
queryColumn()

// 跳转帖子列表页
const toPostList = (columnId) => {
  const {href} = router.resolve(`/post-list/${columnId}`)
  window.open(href, '_blank')
}

// 查询兴趣专栏
const queryInterestColumn = () => {
  if (currentUser !== null) {
    request.get(`/api/contents/posts/special-column/list/${currentUser.id}`).then(res => {
      if (res.code === 1) {
        interestingColumn.value = res.data.filter((col, index) => {
          if (index < 10) {
            return col
          }
        })
        // 给标签添加主题type
        interestingColumn.value.forEach((col, index) => {
          col.type = tagType[index % tagType.length]
        })
      } else {
        Modal.message({message: res.message, status: 'error'})
      }
    })
  }
}
queryInterestColumn()

onUnmounted(() => {
  updateExistFlag() // 显示搜索框
})

</script>

<style lang="less" scoped>
.i-icon {
  cursor: pointer;
}

.main {
  .content {
    .rank {
      .rank-title:hover {
        color: #5E7CE0;
      }
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      cursor: pointer;
    }

    .post-rank {
      .nav {
        div {
          width: 80px;
          margin-left: 20px;
          text-align: center;
          cursor: pointer;
        }

        height: 32px;
        border: 1px solid #ddd;
        background-color: #f8f8f8;
        line-height: 32px;
        margin-bottom: 10px;
      }

      width: 30%;
    }

    .post-list {
      .post-info a:first-child {
        text-decoration: none;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        margin-bottom: 8px;
      }

      .post-info {
        display: flex;
        flex-direction: column;
        margin-bottom: 25px;
      }

      .nav {
        div {
          width: 70px;
          margin-left: 20px;
          text-align: center;
          border-bottom: 2px solid #282b33;
          cursor: pointer;
        }

        height: 32px;
        border: 1px solid #ddd;
        background-color: #f8f8f8;
        line-height: 32px;
        margin-bottom: 20px;
      }

      width: 68%;
    }

    width: 80%;
    height: 100%;
    display: flex;
    margin-top: 20px;
    justify-content: space-between;
  }

  .column-page {
    .page-main {
      .column {
        .base {
          .access-number, .comment-number {
            font-size: 13px;
            color: #949494;
          }

          margin-left: 15px;
          display: flex;
          flex-direction: column;
        }
        width:200px;
        display: flex;
        cursor: pointer;
        margin: 0 20px 10px 0;
      }
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }

    .page-header {
      .page-arrow {
        font-size: 13px;
        font-weight: bold;
        display: flex;
      }

      .title {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
      }

      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    width: 80%;
    border: 1px solid #e6e6e6;
    border-radius: 5px;
    margin-bottom: 20px;
    padding: 10px;
  }

  .user-info {
    .interesting-column {
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }

    .base {
      display: flex;
      margin-bottom: 20px;
      margin-top: 10px;
    }

    width: 200px;
    height: 100%;
    background: #ddd;
    border-radius: 5px;
    transition: border-radius 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    padding: 10px;
  }

  margin-top: 30px;
}

.search-header {
  width: 100%;
  height: 35px;
  background: #333;
  padding: 20px 10px 15px 10px;
  border-radius: 5px;
  margin-left: 7%;
}

.userCol {
  position: sticky;
  top: 0;
}
</style>
